package com.wjr.mvc;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

/**
 * @Author: wjr
 * @Description:
 * @Date Created in  2020-09-09 15:22
 * @Modified By:
 */
@WebServlet(name = "DispatcherServlet")
public class DispatcherServlet extends HttpServlet {

    /**
      * @Description Servlet初始化方法，获取application.properties配备文件的信息
      * @param config
      * @Return void
      * @Author wjr
      * @Date Created in 2020/9/9 15:37
      */
    @Override
    public void init(ServletConfig config) throws ServletException {
        //获取配置文件的路径
        String path = config.getInitParameter("contentConfigLocation");

        //加载配置文件 获取输入流
        InputStream is = DispatcherServlet.class.getClassLoader().getResourceAsStream(path);
        HandlerMapping.loadInputStream(is);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取客户端发来的uri
        String uri = req.getRequestURI();
        //通过映射器反射获取对象
        HandlerMapping.MVCMapping mapping = HandlerMapping.get(uri);
        if (mapping == null){
            resp.sendError(404,"自定义MVC:请求的资源不存在="+uri);
            return;
        }
        Object obj = mapping.getObj();
        Method method = mapping.getMethod();
        //执行获取到的方法
        Object result = null;
        try {
            result = method.invoke(obj, req, resp);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        switch (mapping.getType()){
            case TEXT:
                //如果返回结果是文本，则通过流对象返回
                resp.getWriter().write((String) result);
                break;
            case VIEW:
                //如果返回结果是页面，则重定向
                resp.sendRedirect((String) result);
                break;
        }
    }
}
